/* eslint-disable @typescript-eslint/no-use-before-define */
import { ModalForm, ProFormInstance, ProFormUploadButton } from "@ant-design/pro-components";
import { css } from "@emotion/css";
import { Modal, Tooltip, Typography, Upload } from "antd";
import type { RcFile, UploadProps } from "antd/es/upload";
import type { UploadFile } from "antd/es/upload/interface";
import React, { useRef, useState } from "react";
export type OssUploadFormData = Record<string, unknown> & Partial<File>;
export type OssUploadFormProps = {
	onCancel: (flag?: boolean) => void;
	onSubmit: (values: Array<any>) => Promise<any>;
	open: boolean;
};
const CustomerUploadCardPreview = css`
	.ant-upload-list-item-container {
		width: 170px !important;
		height: 170px !important;
	}
	.ant-upload-select {
		width: 170px !important;
		height: 170px !important;
	}
`;
const CustomerUpload = css`
  width: 170px;
  height: 170px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
`;
const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = error => reject(error);
	});
const UploadForm: React.FC<OssUploadFormProps> = props => {
	const [max] = useState<number>(10);
	// 国际化
	const formRef = useRef<ProFormInstance>();
	const { onCancel, onSubmit, open } = props;
	const [previewOpen, setPreviewOpen] = useState(false);
	const [previewObj, setPreviewObj] = useState<
		| {
				title: string;
				previewImage: any;
		  }
		| undefined
	>(undefined);
	//   const [fileList, setFileList] = useState<UploadFile[]>([
	//     {
	//       uid: '-1',
	//       name: 'image.png',
	//       status: 'done',
	//       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
	//     },
	//     {
	//       uid: '-2',
	//       name: 'image.png',
	//       status: 'done',
	//       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
	//     },
	//     {
	//       uid: '-3',
	//       name: 'image.png',
	//       status: 'done',
	//       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
	//     },
	//     {
	//       uid: '-4',
	//       name: 'image.png',
	//       status: 'done',
	//       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
	//     },
	//   ]);
	// 关闭
	const handleCancel = () => {
		onCancel();
	};
	// 表单提交
	const handleFinish = async (values: Record<string, any>) => {
		console.log(values);
		// @ts-ignore
		return onSubmit({
			...values
		} as Array<any>);
	};

	const handlePreview = async (file: UploadFile) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj as RcFile);
		}

		setPreviewObj({
			previewImage: file.url || (file.preview as string),
			title: file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1)
		});
		setPreviewOpen(true);
	};

	// const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => setFileList(newFileList);

	const handleCancelPreview = () => {
		setPreviewOpen(false);
	};

	const getFileListSize = () => {
		console.log(formRef.current?.getFieldValue("uploads").length);
		return formRef.current?.getFieldValue("uploads")?.length === undefined
			? 0
			: formRef.current?.getFieldValue("uploads")?.length;
	};

	return (
		<>
			<ModalForm<OssUploadFormData>
				title="文件上传"
				open={open}
				width={"48%"}
				autoFocusFirstInput
				grid={true}
				formRef={formRef}
				layout="vertical"
				onFinish={handleFinish}
				modalProps={{
					styles: {
						body: {
							minHeight: "450px"
						}
					},
					centered: true,
					destroyOnClose: true,
					onCancel: () => {
						handleCancel();
					}
				}}
			>
				<ProFormUploadButton
					label={`最大上传数量${max}个`}
					// label={`zui(${getFileListSize()}/${10}个)`}
					listType="picture-card"
					name="files"
					max={max}
					accept=".doc,.docx,.xlsx,.xls,.csv,.ppt,.pptx,.txt,.pdf,.png,.jpg,.jpeg,.gif,.bmp"
					fieldProps={{
						className: CustomerUploadCardPreview,
						onPreview: handlePreview,
						multiple: true,
						maxCount: max,
						beforeUpload: (file, fileList) => {
							if (fileList.length > 10) {
								return Upload.LIST_IGNORE;
							}
							console.log(file, fileList);
							return false;
						}
					}}
				/>
				<Typography.Text type="secondary">
					请上传大小不超过 5MB 的文件{" "}
					<Tooltip
						placement="top"
						title={`.doc, .docx, .xlsx, .xls, .csv, .ppt, .pptx, .txt, .pdf, .png, .jpg, .jpeg, .gif, .bmp`}
					>
						<Typography.Link>查看格式要求</Typography.Link>
					</Tooltip>
				</Typography.Text>
			</ModalForm>
			<Modal open={previewOpen} title={previewObj?.title} footer={null} zIndex={1001} onCancel={handleCancelPreview}>
				<img alt="example" style={{ width: "100%" }} src={previewObj?.previewImage} />
			</Modal>
		</>
	);
};

export default UploadForm;
